package com.lavida.project.system.emp.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.UUID;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.websocket.server.PathParam;

import org.apache.ibatis.annotations.Param;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.aop.ThrowsAdvice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.druid.sql.visitor.functions.Insert;
import com.lavida.common.utils.security.ShiroUtils;
import com.lavida.framework.web.controller.BaseController;
import com.lavida.framework.web.page.TableDataInfo;
import com.lavida.project.common.DownLoadUtils;
import com.lavida.project.common.FileUpload;
import com.lavida.project.system.accumulation.domain.Accumulation;
import com.lavida.project.system.accumulation.domain.Provident;
import com.lavida.project.system.accumulation.service.AccumulationService;
import com.lavida.project.system.dept.domain.Dept;
import com.lavida.project.system.dept.service.IDeptService;
import com.lavida.project.system.emp.domain.Emp;
import com.lavida.project.system.emp.domain.Emphistory;
import com.lavida.project.system.emp.domain.Empleave;
import com.lavida.project.system.emp.domain.Empqt;
import com.lavida.project.system.emp.domain.Roster;
import com.lavida.project.system.emp.service.EmpService;
import com.lavida.project.system.emp.service.EmphistoryService;
import com.lavida.project.system.emp.service.EmpleaveService;
import com.lavida.project.system.emp.service.EmpqtService;
import com.lavida.project.system.emp.service.RosterService;
import com.lavida.project.system.user.domain.User;
import com.lavida.project.system.user.service.IUserService;

@Controller
@RequestMapping("system/emp")
public class EmpController extends BaseController {
	private String prefix = "system/emp";
	@Autowired
	private EmpService empServive;
	@Autowired
	private RosterService rosterService;
	@Autowired
	private AccumulationService accumulationService;
	@Autowired
	private IDeptService deptService;
	@Autowired
	private IUserService userService;
	@Autowired
	private EmpleaveService empleaveService;
	@Autowired
	private EmphistoryService emphistoryService;
	@Autowired
	private EmpqtService empqtService;
	@RequestMapping("/empconcrete")
	public String show(int job_id, HttpServletRequest request,ModelMap mmap){
		User user  = ShiroUtils.getSysUser();
		User user1 = userService.selectUserById(user.getUserId());
		mmap.put("user", user1);
		Emp emp = empServive.selectEmpByempno(job_id);
		System.out.println("emp>>>>>>>>>>>>>>>>>>>>>"+emp);
		request.setAttribute("user", ShiroUtils.getSysUser());
		List<Accumulation> accumulationList = accumulationService.selectAccumulation();
		System.out.println(">>>>>>>>>>>>>>>>>>>>"+accumulationList);
		List<Dept> ddept = deptService.selectDeptListes();
		List<Dept> dept1 = new ArrayList<Dept>();
		List<Dept> dept2 = new ArrayList<Dept>();
		List<Dept> dept3 = new ArrayList<Dept>();
		List<Dept> dept4 = new ArrayList<Dept>();
		for (int i = 0; i < ddept.size(); i++) {
			if (ddept.get(i).getParentId() == 0) {
				dept1.add(ddept.get(i));
			}
			for (int a = 0; a < dept1.size(); a++) {
				if (ddept.get(i).getParentId() == dept1.get(a).getDeptId()) {
					dept2.add(ddept.get(i));
				}
			}
			for (int b = 0; b < dept2.size(); b++) {
				if (ddept.get(i).getParentId() == dept2.get(b).getDeptId()) {
					dept3.add(ddept.get(i));
				}
			}
			for (int c = 0; c < dept3.size(); c++) {
				if (ddept.get(i).getParentId() == dept3.get(c).getDeptId()) {
					dept4.add(ddept.get(i));
				}
			}
		}
		request.setAttribute("dept1", dept1);
		request.setAttribute("dept2", dept2);
		request.setAttribute("dept3", dept3);
		request.setAttribute("dept4", dept4);
		request.setAttribute("user", ShiroUtils.getSysUser());
		if (emp != null) {
			request.setAttribute("emp", emp);
			request.setAttribute("accumulationList", accumulationList);
		}
		return prefix + "/emp";
	}

	// 文件上传
	@RequestMapping("/update")
	public String update(MultipartFile Befoleavefile1, MultipartFile academiccer1, MultipartFile procer1,
			MultipartFile copyfile1, MultipartFile laborhand1, MultipartFile mereport1, MultipartFile sopaytcer1,
			MultipartFile recordpro1, MultipartFile cardpicture1, MultipartFile card1, MultipartFile banknum1,
			MultipartFile leavefile1, MultipartFile laborcontract1, MultipartFile otherdata1,MultipartFile empphoto1,
			int job_id,HttpServletRequest request, Emp emp) {
		System.out.println("user>>>>>>>" + emp);
		Emp emp1 = empServive.selectEmpByempno(job_id);
		Roster roster = rosterService.getRoster(job_id);
		Provident provident = accumulationService.ProselectById(1);
		if (emp.getSocialbase() < provident.getSocialBaseBelow()) {
			emp.setSocialbase(provident.getSocialBaseBelow());
		} else if (emp.getSocialbase() > provident.getSocialBaseTop()) {
			emp.setSocialbase(provident.getSocialBaseTop());
		} else {
			emp.setSocialbase(emp.getSocialbase());
		}
		
		if (emp.getPublicbase() < provident.getAccumuBaseBelow()) {
			emp.setPublicbase(provident.getAccumuBaseBelow());
		} else if (emp.getPublicbase() > provident.getAccumuBaseTop()) {
			emp.setPublicbase(provident.getAccumuBaseTop());
		} else {
			emp.setPublicbase(emp.getPublicbase());
		}
		emp.setBefoleavefile(
				Befoleavefile1.isEmpty() ? emp1.getBefoleavefile() : getFilenameUUID(Befoleavefile1, request));
		emp.setAcademiccer(academiccer1.isEmpty() ? emp1.getAcademiccer() : getFilenameUUID(academiccer1, request));
		emp.setProcer(procer1.isEmpty() ? emp1.getProcer() : getFilenameUUID(procer1, request));
		emp.setCopyfile(copyfile1.isEmpty() ? emp1.getCopyfile() : getFilenameUUID(copyfile1, request));
		emp.setLaborhand(laborhand1.isEmpty() ? emp1.getLaborhand() : getFilenameUUID(copyfile1, request));
		emp.setMereport(mereport1.isEmpty() ? emp1.getMereport() : getFilenameUUID(mereport1, request));
		emp.setSopaytcer(sopaytcer1.isEmpty() ? emp1.getSopaytcer() : getFilenameUUID(sopaytcer1, request));
		emp.setRecordpro(recordpro1.isEmpty() ? emp1.getSopaytcer() : getFilenameUUID(recordpro1, request));
		emp.setCardpicture(cardpicture1.isEmpty() ? emp1.getCardpicture() : getFilenameUUID(cardpicture1, request));
		emp.setCard(card1.isEmpty() ? emp1.getCard() : getFilenameUUID(card1, request));
		emp.setBanknum(banknum1.isEmpty() ? emp1.getBanknum() : getFilenameUUID(banknum1, request));
		emp.setLeavefile(leavefile1.isEmpty() ? emp1.getLeavefile() : getFilenameUUID(leavefile1, request));
		emp.setLaborcontract(
				laborcontract1.isEmpty() ? emp1.getLaborcontract() : getFilenameUUID(laborcontract1, request));
		emp.setOtherdata(otherdata1.isEmpty() ? emp1.getOtherdata() : getFilenameUUID(otherdata1, request));
		emp.setEmpphoto(empphoto1.isEmpty() ? emp1.getEmpphoto() : getFilenameUUID(empphoto1, request));
		Accumulation coverage1 = accumulationService.selectBycoverage("基本养老保险");
		Accumulation coverage2 = accumulationService.selectBycoverage("基本医疗保险");
		Accumulation coverage3 = accumulationService.selectBycoverage("地方附加医疗保险");
		Accumulation coverage4 = accumulationService.selectBycoverage("失业保险");
		Accumulation coverage5 = accumulationService.selectBycoverage("工伤保险");
		Accumulation coverage6 = accumulationService.selectBycoverage("生育保险");
		Accumulation coverage7 = accumulationService.selectBycoverage("残疾人保险");
		Accumulation coverage8 = accumulationService.selectBycoverage("住房公积金");

		Double money_basicoldcomcost = coverage1 != null
				? (emp.getSocialbase()) * (Double.parseDouble(coverage1.getCompanyRate()) * 0.01)
				: null;
		Double money_basicoldpercost = coverage1 != null
				? (emp.getSocialbase()) * (Double.parseDouble(coverage1.getPersonalRate()) * 0.01)
				: null;
		Double money_basicdoccomcost = coverage2 != null
				? (emp.getSocialbase()) * (Double.parseDouble(coverage2.getCompanyRate()) * 0.01)
				: null;
		Double money_basicdocpercost = coverage2 != null
				? (emp.getSocialbase()) * (Double.parseDouble(coverage2.getPersonalRate()) * 0.01)
				: null;
		Double money_localdoccomcost = coverage3 != null
				? (emp.getSocialbase()) * (Double.parseDouble(coverage3.getCompanyRate()) * 0.01)
				: null;
		Double money_localdocpercost = coverage3 != null
				? (emp.getSocialbase()) * (Double.parseDouble(coverage3.getPersonalRate()) * 0.01)
				: null;
		Double money_unemploymentcomcost = coverage4 != null
				? (emp.getSocialbase()) * (Double.parseDouble(coverage4.getCompanyRate()) * 0.01)
				: null;
		Double money_unemploymentpercost = coverage4 != null
				? (emp.getSocialbase()) * (Double.parseDouble(coverage4.getPersonalRate()) * 0.01)
				: null;
		Double money_injuryinsurancecomcost = coverage5 != null
				? (emp.getSocialbase()) * (Double.parseDouble(coverage5.getCompanyRate()) * 0.01)
				: null;
		Double money_injuryinsurancepercost = coverage5 != null
				? (emp.getSocialbase()) * (Double.parseDouble(coverage5.getPersonalRate()) * 0.01)
				: null;
		Double money_materyinsurancecomcost = coverage6 != null
				? (emp.getSocialbase()) * (Double.parseDouble(coverage6.getCompanyRate()) * 0.01)
				: null;
		Double money_materyinsurancepercost = coverage6 != null
				? (emp.getSocialbase()) * (Double.parseDouble(coverage6.getPersonalRate()) * 0.01)
				: null;
		Double money_disableinsurancecomcost = coverage7 != null
				? (emp.getSocialbase()) * (Double.parseDouble(coverage7.getCompanyRate()) * 0.01)
				: null;
		Double money_disableinsurancepercost = coverage7 != null
				? (emp.getSocialbase()) * (Double.parseDouble(coverage7.getPersonalRate()) * 0.01)
				: null;
		Double money_providentfundcomcost = coverage8 != null
				? (emp.getPublicbase()) * (Double.parseDouble(coverage8.getCompanyRate()) * 0.01)
				: null;
		Double money_providentfundpercost = coverage8 != null
				? (emp.getPublicbase()) * (Double.parseDouble(coverage8.getPersonalRate()) * 0.01)
				: null;
		roster.setJob_id(job_id + "");
		roster.setName(emp.getName());
		roster.setCompany(emp.getCompany());
		roster.setFen_company(emp.getFen_company());
		roster.setDept(emp.getDept());
		roster.setGroup(emp.getCgroup());
		roster.setGangwei(emp.getGangwei());
		roster.setHiredate(emp.getHiredate());
		roster.setStatus(emp.getStatus());
		roster.setLeavetime(emp.getLeavetime());
		roster.setId_card(emp.getId_card());
		roster.setContract_term(emp.getContract_term());
		roster.setContract_id(emp.getLaborcontract());
		rosterService.updateRoster(roster);
		Empleave empleave = empleaveService.selectEmpleaveById(emp.getJob_id());
		if (empleave==null) {
			Empleave empleave1 = new Empleave();
			empleave1.setJobId(Integer.valueOf(roster.getJob_id()));
			empleave1.setName(roster.getName());
			empleave1.setYwjiao("业务文件交接");
			empleave1.setGzquntc("工作群退出");
			empleave1.setLzyxtzhi("离职邮件通知");
			empleave1.setJkjjie("借款交接");
			empleave1.setGzzjiaojie("工作证交接");
			empleave1.setYgscjiaojie("员工手册交接");
			empleave1.setKqgb("考勤关闭");
			empleave1.setDdgb("钉钉关闭");
			empleave1.setGxgb("共享关闭");
			empleave1.setYxgb("邮箱关闭");
			empleave1.setBxgb("报销关闭");
			empleave1.setDnzh("电脑账号关闭");
			empleave1.setXtgb("系统关闭");
			empleave1.setBgyb("办公用品交接");
			empleave1.setYsjiaojie("钥匙交接");
			empleave1.setGsquntc("公司群退出");
			empleave1.setWbzhjj("外部账号交接");
			empleave1.setWbzhzx("外部账号注销");
			empleave1.setGzff("工资发放");
			empleave1.setLdsc("劳动手册");
			empleave1.setTgd("退工单");
			empleave1.setZlbf("资料备份");
			empleaveService.insertEmpleave(empleave1);
		}else {
			empleave.setDept(emp.getDept());
			if (emp.getEstimatedtime()!=null) {
				empleave.setEstimatedtime(emp.getEstimatedtime()+"");
			}
			empleaveService.updateEmpleavebf(empleave);
		}
		money_basicoldcomcost = new BigDecimal(money_basicoldcomcost).setScale(1, RoundingMode.UP).doubleValue();
		money_basicoldpercost = new BigDecimal(money_basicoldpercost).setScale(1, RoundingMode.UP).doubleValue();
		money_basicdoccomcost = new BigDecimal(money_basicdoccomcost).setScale(1, RoundingMode.UP).doubleValue();
		money_basicdocpercost = new BigDecimal(money_basicdocpercost).setScale(1, RoundingMode.UP).doubleValue();
		money_basicdocpercost = new BigDecimal(money_basicdocpercost).setScale(1, RoundingMode.UP).doubleValue();
		money_localdocpercost = new BigDecimal(money_localdocpercost).setScale(1, RoundingMode.UP).doubleValue();
		money_localdocpercost = new BigDecimal(money_localdocpercost).setScale(1, RoundingMode.UP).doubleValue();
		money_localdocpercost = new BigDecimal(money_localdocpercost).setScale(1, RoundingMode.UP).doubleValue();
		money_unemploymentpercost = new BigDecimal(money_unemploymentpercost).setScale(1, RoundingMode.UP).doubleValue();
		money_injuryinsurancecomcost = new BigDecimal(money_injuryinsurancecomcost).setScale(1, RoundingMode.UP).doubleValue();
		money_injuryinsurancepercost = new BigDecimal(money_injuryinsurancepercost).setScale(1, RoundingMode.UP).doubleValue();
		money_materyinsurancecomcost = new BigDecimal(money_materyinsurancecomcost).setScale(1, RoundingMode.UP).doubleValue();
		money_materyinsurancepercost = new BigDecimal(money_materyinsurancepercost).setScale(1, RoundingMode.UP).doubleValue();
		money_disableinsurancecomcost = new BigDecimal(money_disableinsurancecomcost).setScale(1, RoundingMode.UP).doubleValue();
		money_disableinsurancepercost = new BigDecimal(money_disableinsurancepercost).setScale(1, RoundingMode.UP).doubleValue();
		money_providentfundcomcost = new BigDecimal(money_providentfundcomcost).setScale(0, RoundingMode.HALF_UP).doubleValue();
		money_providentfundpercost = new BigDecimal(money_providentfundpercost).setScale(0, RoundingMode.HALF_UP).doubleValue();
		emp.setBasicoldcomcost(money_basicoldcomcost);
		emp.setBasicoldpercost(money_basicoldpercost);
		emp.setBasicdoccomcost(money_basicdoccomcost);
		emp.setBasicdocpercost(money_basicdocpercost);
		emp.setLocaldoccomcost(money_basicdocpercost);
		emp.setLocaldocpercost(money_localdocpercost);
		emp.setUnemploymentcomcost(money_localdocpercost);
		emp.setUnemploymentpercost(money_unemploymentpercost);
		emp.setInjuryinsurancecomcost(money_injuryinsurancecomcost);
		emp.setInjuryinsurancepercost(money_injuryinsurancepercost);
		emp.setMateryinsurancecomcost(money_materyinsurancecomcost);
		emp.setMateryinsurancepercost(money_materyinsurancepercost);
		emp.setDisableinsurancecomcost(money_disableinsurancecomcost);
		emp.setDisableinsurancepercost(money_disableinsurancepercost);
		emp.setProvidentfundcomcost(money_providentfundcomcost);
		emp.setProvidentfundpercost(money_providentfundpercost);
		//计算公司缴纳总费用
		Double companysumpay =money_basicoldcomcost+money_basicdoccomcost+money_localdoccomcost+money_unemploymentcomcost
				+money_injuryinsurancecomcost+money_materyinsurancecomcost+money_disableinsurancecomcost+money_providentfundcomcost;
		//个人缴纳总费用费用
		Double personsumpay=money_basicoldpercost + money_basicdocpercost + money_localdocpercost + money_unemploymentpercost + money_injuryinsurancepercost
				+money_materyinsurancepercost + money_disableinsurancepercost + money_providentfundpercost;
		//总费用
		Double sumpay = companysumpay+personsumpay;
		emp.setCompanysumpay(companysumpay);
		emp.setPersonsumpay(personsumpay);
		emp.setSumpay(sumpay);
		System.out.println("emp>>>>>>>>>>>>>>>"+emp);
		empServive.updateEmp(emp);
		request.setAttribute("user", ShiroUtils.getSysUser());
		request.setAttribute("emp", emp);

		return "redirect:empconcrete?job_id=" + job_id;
	}
	@PostMapping("/historylist/{job_id}")
	@ResponseBody
	public TableDataInfo list(@PathVariable("job_id")Integer job_id) {
		Emphistory emphistory = new Emphistory();
		List<Emphistory> selectEmphistory = emphistoryService.selectEmphistoryById(job_id);
		System.out.println(selectEmphistory.toString());
		return getDataTable(selectEmphistory);
	}
	@PostMapping("/updatehistory")
	public String updalplist(Emphistory emphistory,@Param("file2") MultipartFile file2,HttpServletRequest request) {
		emphistory.setFufile(file2.getOriginalFilename());
		emphistory.setFufilepath(file2.isEmpty() ? emphistory.getFufilepath() : getFilenameUUID(file2, request));
		emphistoryService.updateEmphistory(emphistory);
		return "redirect:empconcrete?job_id=" + emphistory.getJob_id();
	}
	@PostMapping("/insertHistory")
	public String insertHistory(Emphistory emphistory,@Param("file2") MultipartFile file2,HttpServletRequest request) {
		Integer job_id  = emphistory.getJob_id();
		if(emphistory.getTypes().equals("年度调薪") || emphistory.equals("其它")) {
			if (file2.isEmpty()) {
				emphistory.setFufile(null);
				emphistory.setFufilepath(null);
			}
		}else {
			emphistory.setFufile(file2.getOriginalFilename());
			emphistory.setFufilepath(file2.isEmpty() ? emphistory.getFufilepath() : getFilenameUUID(file2, request));
		}
		emphistoryService.insertEmphistory(emphistory);
		return "redirect:empconcrete/?job_id=" + job_id;
	}
	@PostMapping("/getHistory")
	@ResponseBody
	public Map<String, Object> getHistory(Integer id,HttpServletRequest request) {
		Map<String, Object> result = new HashMap<String, Object>();
		Emphistory emphistory  = emphistoryService.selectEmphistoryByIdr(id);
		result.put("emphistory", emphistory);
		return result;
	}
	@PostMapping("/deleteHistory")
	@ResponseBody
	public Map<String, Object> deleteHistory(@RequestParam("ids[]")int[] ids) {
		Map<String, Object> result = new HashMap<String, Object>();
		emphistoryService.deleteEmphistory(ids);
		result.put("msg", 1);
		return result;
	}
	@PostMapping("/Empqtlist/{job_id}")
	@ResponseBody
	public TableDataInfo empqtlist(@PathVariable("job_id")Integer job_id) {
		Empqt empqt = new Empqt();
		List<Empqt> selectEmpqt = empqtService.selectEmpqtById(job_id);
		System.out.println(selectEmpqt.toString());
		return getDataTable(selectEmpqt);
	}
	@PostMapping("/updateEmpqt")
	public String empqtlist(Empqt empqt) {
		empqtService.updateEmpqt(empqt);
		return "redirect:empconcrete?job_id=" + empqt.getJob_id();
	}
	@PostMapping("/insertEmpqts")
	public String insertEmpqt(Empqt empqt) {
		int i = empqtService.insertEmpqt(empqt);
		return "redirect:empconcrete?job_id=" + empqt.getJob_id();
	}
	@PostMapping("/getEmpqt")
	@ResponseBody
	public Map<String, Object> getempqt(Integer id,HttpServletRequest request) {
		Map<String, Object> result = new HashMap<String, Object>();
		Empqt empqt  = empqtService.selectEmpqtByIdr(id);
		result.put("empqt", empqt);
		return result;
	}
	@PostMapping("/deleteEmpqt")
	@ResponseBody
	public Map<String, Object> deletermpqt(@RequestParam("ids[]")int[] ids) {
		Map<String, Object> result = new HashMap<String, Object>();
		empqtService.deleteEmpqt(ids);
		result.put("msg", 1);
		return result;
	}
	// 文件下载
	@RequestMapping("/download")
	public void download(String filename, HttpServletRequest request, HttpServletResponse response) {
		String string = request.getHeader("User-Agent");
		String Uploadfilename = null;
		try {

			Uploadfilename = DownLoadUtils.getFileName(string,
					String.format(filename.substring(filename.indexOf("_") + 1)));
			response.setHeader("Content-disposition", "attachment;filename=" + Uploadfilename);
			String fileVmPath = FileUpload.filePath(request);

			ServletOutputStream s = response.getOutputStream();
			BufferedInputStream bufferedInputStream = new BufferedInputStream(
					new FileInputStream(String.format("%s/%s", fileVmPath, filename)));
			int a;
			byte[] bytes = new byte[1024];
			while ((a = bufferedInputStream.read(bytes)) != -1) {
				s.write(bytes, 0, a);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	private String getFilenameUUID(MultipartFile file, HttpServletRequest request) {

		String path = FileUpload.filePath(request);
		String originalFilename = file.getOriginalFilename();

		String uuid = UUID.randomUUID().toString().replace("-", "");
		String filename = uuid + "_" + originalFilename;
		try {
			file.transferTo(new File(path, filename));
		} catch (Exception e) {
			// TODO: handle exception
		}
		return filename;
	}
}
